// 新建 src/components/LimitCount.jsx
import React, { useState, useEffect } from 'react';
import { ImageUploader, Dialog, Toast } from 'antd-mobile';
import axios from 'axios';
import { v4 as uuidv4 } from 'uuid';

export const LimitCount = ({ maxCount = 3, onFileListChange,value }) => {
    const [fileList, setFileList] = useState([]);

    //初始化
    useEffect(() => {
        setFileList(value);
    }, []);

    // 将状态变化同步给父组件
    useEffect(() => {
        onFileListChange?.(fileList);
    }, [fileList]);

    // 原有 customUpload 和 handleDelete 逻辑...
    // 自定义上传逻辑
    const customUpload = async (file) => {
        return new Promise((resolve, reject) => {
            const formData = new FormData();
            formData.append('image', file);

            axios.post('http://geek.itheima.net/v1_0/upload', formData, {
                headers: {
                    'Content-Type': 'multipart/form-data',
                },
            })
                .then((response) => {
                    // console.log('上传成功1', response);
                    // console.log('上传成功2', file);
                    // console.log('上传成功3', response.data.data.url);

                    if (response.data && response.data.data.url) {
                        resolve({
                            uid: uuidv4(),
                            name: file.name,
                            status: 'done',
                            url: response.data.data.url, // 使用接口返回的图片 URL
                        });
                        // Toast.show('上传成功');
                    } else {
                        Toast.show('上传失败：未获取到图片 URL');
                        reject(new Error('未获取到图片 URL'));
                    }
                })
                .catch((error) => {
                    Toast.show('上传失败，请稍后重试');
                    reject(error);
                });
        });
    };

    // 删除确认
    const handleDelete = (index) => {
        return Dialog.confirm({
            content: '是否确认删除',
            onConfirm: () => {
                setFileList(fileList.filter((_, i) => i !== index));
            },
        });
    };
    const uploaderProps = {
        value: fileList,
        onChange: setFileList,
        upload: customUpload,
        maxCount, // 限制最多上传 3 张图片
        onDelete: handleDelete,
        multiple:true
    }


    return <ImageUploader {...uploaderProps} />;
};